# coding=utf-8
import time
from datetime import datetime, timedelta
from queue import Queue
from threading import Thread

import dingding
import settings
import sina

rise_cache = sina.RiseCache()
analyze_queue = Queue()
body_queue = Queue()


def analyze():
    while True:
        measure_list: list[sina.StockMeasure] = analyze_queue.get()
        try:
            for i in measure_list:

                if rise_cache.amplitude(i.code) >= settings.STOCKS.amplitude_alert_threshold(i.code):
                    body_queue.put(dingding.price_warn_body(i))

        finally:
            analyze_queue.task_done()


def notice():
    while True:
        body = body_queue.get()
        try:
            dingding.send(body, settings.ACCESS_TOKEN, settings.SECRET)
        finally:
            body_queue.task_done()


Thread(target=analyze, daemon=True).start()
Thread(target=notice, daemon=True).start()

now = datetime.now()
today = datetime(year=now.year, month=now.month, day=now.day)
am_1 = today + timedelta(hours=9, minutes=25)
am_2 = today + timedelta(hours=11, minutes=30)
pm_1 = today + timedelta(hours=13)
pm_2 = today + timedelta(hours=15)

while True:
    now = datetime.now()
    if am_1 <= now <= am_2 or pm_1 <= now <= pm_2:
        data = sina.get_stock_data(settings.STOCKS)
        rise_cache.batch_put(data)
        analyze_queue.put(data)

        if settings.SEND_REAL_PRICE:
            body_queue.put(dingding.real_price_body(data, msg_type="text"))

        interval = settings.COLLECT_INTERVAL
    elif now < am_1:
        interval = (am_1 - now).seconds
        print(f"not open, wait {interval} seconds")
    elif am_2 < now < pm_1:
        interval = (pm_1 - now).seconds
        print(f"afternoon close, wait {interval} seconds")
    else:
        print("market close!")
        break

    time.sleep(interval)
